import '../Scss/Mars3dList.scss'
import { useRef, useEffect, useState } from 'react'
import { FloatButton, Select, Button, Tree, Spin, Empty, Tag } from 'antd'
import { useBoolean, useEventEmitter, useMount, useRequest } from 'ahooks'
import { Initialization } from '../../Mars3d/Initialization'
import { EditOutlined, SaveOutlined } from '@ant-design/icons'
import { wallList } from '../../Mars3d/style'
import { Http } from '../../Api'

const { CheckableTag } = Tag

const scene = {
    basemaps: '3',
    layers: null,
    center: '{ "lat": 41.726139, "lng": 127.724575, "alt": 900724.7, "heading": 357.8, "pitch": -59.5 }',
}

const { mars3d, Cesium } = window

export const FenceMapModal = ({ data, Off }) => {
    const MapBox = useRef()
    const { actionRef, record } = data.data
    const { uuid, tableName } = record
    const [Gra, setGra] = useState()
    const [DrawFunc, setDrawFunc] = useState()
    const [SaveShow, { setTrue, setFalse }] = useBoolean(false)
    const [coordinates, setCoordinates] = useState(record.coordinates)
    const { style } = wallList(tableName, 1, 1, 500, 8, '#f0f')['wall008']
    const { runAsync } = useRequest(Http, { manual: true })
    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra }) => {
        setGra(gra)
        const drawFunc = new mars3d.layer.GraphicLayer({ hasEdit: true })
        setDrawFunc(drawFunc)
        map.addLayer(drawFunc)
        if (record.coordinates) {
            const Wall = new mars3d.graphic.WallEntity({ id: uuid, positions: record.coordinates, style })
            gra.addGraphic(Wall)
            Wall.flyTo({ radius: 1000, pitch: -45 })
        }
    })

    const DrawFence = () => {
        if (DrawFunc) {
            Gra.clear()
            DrawFunc.clear()
            setFalse()
            DrawFunc.startDraw({ type: 'wall', style }).then(res => {
                setCoordinates(res.coordinates)
                setTrue()
            })
        }
    }

    const SaveFence = () => {
        runAsync({ url: 'posFenceCoordinates', data: coordinates, path: [uuid] }).then(res => {
            actionRef.current.reload()
            Off()
        })
    }

    useEffect(() => {
        Initialization(scene, MapBox, InitializationEvent)
    }, [InitializationEvent])
    return (
        <div className="FenceMapModal">
            <div className="FenceMap" ref={MapBox} />
            {SaveShow && (
                <FloatButton
                    onClick={SaveFence}
                    icon={<SaveOutlined />}
                    type="primary"
                    style={{ right: 54, bottom: 104 }}
                />
            )}
            <FloatButton onClick={DrawFence} icon={<EditOutlined />} type="primary" style={{ right: 54 }} />
        </div>
    )
}
//
const initMars3 = {
    scene: {
        center: { lat: 45.263334, lng: 124.222042, alt: 4495185.1, heading: 360, pitch: -89.8 },
        showSun: false,
        showMoon: false,
        showSkyBox: false,
        showSkyAtmosphere: false,
        fog: false,
        backgroundColor: '#363635',
        // contextOptions: { webgl: { antialias: !mobilecheck() } },
        globe: { baseColor: '#363635', showGroundAtmosphere: false, enableLighting: false },
        clock: { currentTime: '2023-11-01 12:00:00' },
        cameraController: {
            zoomFactor: 1.5,
            minimumZoomDistance: 0.1,
            maximumZoomDistance: 200000,
            enableCollisionDetection: false,
        },
    },
    layers: [{ name: '网格线', type: 'grid', color: '#ffffff', alpha: 0.03, cells: 2, show: true }],
}

const modalMapping = {
    'ad503a25-8ad0-4c60-b1fe-e83341cedf09': 'f1eed8fd-3240-44a8-a16d-2af9e7033911',
}

const colorMapping = {
    default: 'rgba(255,255,255,1)',
    hide: 'rgba(255,255,255,0.03)',
    select: 'rgba(0,255,0,0.8)',
    record: 'rgba(255,0,0,0.8)',
}

export const Mars3DPlannedProgress = ({ data }) => {
    const MapDiv = useRef()
    const { tableName, organizationUuid } = data.data.record

    const [Map, setMap] = useState()
    const [Gra, setGra] = useState()

    const [Json, setJson] = useState()
    const [Plan, setPlan] = useState()

    const [ModalUuid, setModalUuid] = useState()
    const [FilesUuid, setFilesUuid] = useState()
    const [ModalList, setModalList] = useState()
    const [TreeData, setTreeData] = useState()
    const [Tiles, setTiles] = useState()

    const [RightStatus, setRightStatus] = useState(false)
    const [RightTitle, setRightTitle] = useState()
    const [RightData, setRightData] = useState()

    const [SelectDbId, setSelectDbId] = useState([])

    const { runAsync: getJson } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            if (res) {
                if (!res[tableName]) {
                    const data = JSON.stringify(JSON.stringify({ ...res, [tableName]: {} }))
                    posJson({ url: 'posSaveJsonInfoByUuid', data, path: [`plan${organizationUuid}`] })
                } else {
                    setJson(res)
                    getModal({ url: 'getBimFileOrganizationRelation', data: { organizationUuid } })
                }
            } else {
                const json = { [tableName]: {} }
                const data = JSON.stringify(JSON.stringify(json))
                posJson({ url: 'posSaveJsonInfoByUuid', data, path: [`plan${organizationUuid}`] })
            }
        },
    })

    const { runAsync: posJson } = useRequest(Http, {
        manual: true,
        onSuccess: () => getJson({ url: 'getJsonInfoByUuid', data: { uuid: `plan${organizationUuid}` } }),
    })

    const { runAsync: getModal } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            console.log('开始获取模型数据')
            setModalList(res.list)
            if (res.list.length === 1) initMapFunc(res.list[0])
            else initMapFunc()
        },
    })

    const { runAsync: getTree } = useRequest(Http, { manual: true, onSuccess: res => setTreeData(res[0].children) })

    const initMapFunc = data => {
        const map = new mars3d.Map(MapDiv.current, initMars3)
        const gra = new mars3d.layer.GraphicLayer()
        setMap(map)
        setGra(gra)
        if (data) initModal(map, data)
    }

    const initModal = (map, data) => {
        const { [tableName]: _, ...newObj } = Json
        console.log('[````````````数组组装--开始`````````````````]')
        console.log('[当前月份数据]', Json[tableName])
        console.log('[其他月份数据]', newObj)
        console.log(Json)
        console.log('[````````````数组组装--结束`````````````````]')

        // const { uuid, url, bimFilesUuid } = data
        // if (map.getLayerById(ModalUuid)) map.removeLayer(map.getLayerById(ModalUuid))
        // const tiles = new mars3d.layer.TilesetLayer({
        //     url: NewMapUrl + url,
        //     id: uuid,
        //     allowDrillPick: e => {
        //         console.log(e)
        //         const alpha = e.pickedObject.color.alpha
        //         if (Cesium.defined(alpha) && alpha !== 1) return true
        //         return false
        //     },
        //     flyTo: true
        // })
        // map.addLayer(tiles)
        // setTiles(tiles)
        // setModalUuid(uuid)
        // setFilesUuid(bimFilesUuid)
        // 初始化模型render
    }

    const flyTo = () => {
        Map.flyToGraphic(Tiles)
    }

    useMount(() => {
        getTree({ url: 'getconstructionTrees', path: ['15f196ef3-98f5-4e1a-a1e7-18f3d7fad4a'] })
        getJson({ url: 'getJsonInfoByUuid', data: { uuid: `plan${organizationUuid}` } })
    })

    const { runAsync: getTreeItem } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            DbIdRenderColor(res.list, SelectDbId)
            setRightData(res.list)
        },
    })
    const { runAsync: getItemDetal } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            console.log('[模型详细信息]', res)
        },
    })

    const onSelect = (_, { node }) => {
        if (node.lowLevel === 0) {
            const { fullName, uuid } = node
            setRightTitle(fullName)
            setRightStatus(true)
            setRightData()
            getTreeItem({ url: 'getModelsInfo', data: { FilesUuid, constructionTreeUuid: uuid } })
        }
    }

    const handleChange = (dbid, checked) => {
        const nextSelectedTags = checked ? [...SelectDbId, dbid] : SelectDbId.filter(v => v !== dbid)
        setSelectDbId(nextSelectedTags)
        DbIdRenderColor(RightData, nextSelectedTags)
    }

    const DbIdRenderColor = (resData, selData) => {
        const resDataArray = resData.filter(item => !selData.includes(item.dbId))
        const selDataArray = selData.filter(item => resData.some(obj => obj.dbId === item))

        // eslint-disable-next-line no-template-curly-in-string
        const dbidList = resDataArray.map(({ dbId }) => ['${DbId}===' + dbId, colorMapping.default])
        // eslint-disable-next-line no-template-curly-in-string
        const dbidSele = selDataArray.map(dbId => ['${DbId}===' + dbId, colorMapping.select])
        Tiles.style = new Cesium.Cesium3DTileStyle({
            color: { conditions: [...dbidList, ...dbidSele, ['true', colorMapping.hide]] },
        })

        // console.log('[resData]', resData)
        // console.log('[selData]', selData)
    }

    useEffect(() => {
        if (Tiles && Tiles) {
            // console.log('[模型可以点击了]')
            Tiles.on(mars3d.EventType.click, e => {
                const { DbId } = e.graphic.attr
                getItemDetal({ url: 'getModelsInfo', data: { FilesUuid, DbId, pageIndex: 1, pageSize: 1 } })
            })
        }
    }, [FilesUuid, Tiles, getItemDetal])

    return (
        <div className="Mars3DPlannedProgress">
            <div className="Map" ref={MapDiv} />
            {ModalList ? (
                ModalList.length > 1 && !ModalUuid && <div className="Center">请先选择模型</div>
            ) : (
                <div className="Center">加载...</div>
            )}
            {ModalUuid && TreeData && (
                <div className="Left">
                    <Tree
                        className="treeDele"
                        treeData={[TreeData.find(v => v.uuid === modalMapping[ModalUuid])]}
                        fieldNames={{ title: 'tableName', key: 'uuid' }}
                        onSelect={onSelect}
                    />
                </div>
            )}

            {RightStatus && (
                <div className="Right">
                    <div className="Title">{RightTitle}</div>
                    {RightData ? (
                        RightData.length !== 0 ? (
                            <div className="box">
                                {RightData.map(({ dbId, tableName }) => {
                                    return (
                                        <CheckableTag
                                            key={dbId}
                                            checked={SelectDbId.includes(dbId)}
                                            onChange={checked => handleChange(dbId, checked)}
                                        >
                                            {tableName}
                                        </CheckableTag>
                                    )
                                })}
                            </div>
                        ) : (
                            <Empty />
                        )
                    ) : (
                        <Spin />
                    )}
                </div>
            )}

            <div className="Bottom">
                <Select
                    style={{ flex: 1, marginRight: 16 }}
                    value={ModalUuid}
                    onChange={e =>
                        initModal(
                            Map,
                            ModalList.find(v => v.uuid === e),
                        )
                    }
                    fieldNames={{ value: 'uuid', label: 'bim_FilesName' }}
                    options={ModalList}
                />
                <Button type="primary" onClick={flyTo}>
                    视角回归
                </Button>
            </div>
        </div>
    )
}
